package io.zcoder.innoway.activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.zcoder.innoway.R;
import io.zcoder.innoway.utils.Utils;
import io.zcoder.innoway.adapters.ProfileAdapter;
import io.zcoder.innoway.commons.Constants;
import io.zcoder.innoway.commons.PrefUtils;
import io.zcoder.innoway.models.Profile;
import io.zcoder.innoway.models.ProfilesResponse;
import io.zcoder.innoway.models.ResponseBase;
import io.zcoder.innoway.rest.RestClient;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class FamilyMembersActivity extends BaseActivity implements ProfileAdapter.ProfileCallBack {

    public static final int REQUEST_SET_PASS_CODE = 111;
    public static final int REQUEST_REMOVE_PASS_CODE = 222;
    public static final int REQUEST_ADD_PROFILE = 333;

    @BindView(R.id.listView)
    ListView mListView;
    @BindView(R.id.add_member)
    LinearLayout mLayoutAdd;

    @OnClick(R.id.add_member)
    void add() {
        if (mProfileMainId == 0) {
            return;
        }
        startActivityForResult(new Intent(this, AddProfileActivity.class), REQUEST_ADD_PROFILE);
    }

    private int mProfileMainId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_family_member_activity);
        ButterKnife.bind(this);
        showBack(true);
        setTitle(getString(R.string.family_member));

        getData();
    }

    private void getData() {
        RestClient.build(this, true).getProfileMembers(new Callback<ProfilesResponse>() {
            @Override
            public void success(ProfilesResponse profilesResponse, Response response) {
                if (profilesResponse.getStatus_code() != 200) {
                    showAlert(getString(R.string.error), profilesResponse.getMessage());
                } else {
                    ProfileAdapter adapter = new ProfileAdapter(FamilyMembersActivity.this, profilesResponse.getData());
                    mProfileMainId = adapter.getProfileMainId();
                    if (PrefUtils.getInt(FamilyMembersActivity.this, PrefUtils.PREF_PROFILE_ID) == mProfileMainId) {
                        mLayoutAdd.setVisibility(View.VISIBLE);
                    } else {
                        mLayoutAdd.setVisibility(View.VISIBLE);
                    }
                    mListView.setAdapter(adapter);
                }
            }

            @Override
            public void failure(RetrofitError error) {
            }
        });
    }

    @Override
    public void onSelectProfile(Profile profile) {
        if (Utils.isBlank(profile.getPasscode())) {
            PrefUtils.setInt(this, PrefUtils.PREF_PROFILE_ID, profile.getId());
            setResult(RESULT_OK);
            finish();
        } else {
            inputPassCode(profile);
        }
    }

    @Override
    public void optionProfileFromMain(final Profile profile) {
        MaterialDialog.Builder builder = new MaterialDialog.Builder(this);
        builder.items(R.array.delete_user);
        builder.negativeText(R.string.cancel)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                        new MaterialDialog.Builder(FamilyMembersActivity.this)
                                .title(R.string.delete_user)
                                .content(R.string.are_you_sure)
                                .positiveText(R.string.yes)
                                .negativeText(R.string.no)
                                .onPositive(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                        deleteUser(profile.getId());
                                    }
                                }).show();

                    }
                }).show();
    }

    private void deleteUser(int id) {
        showProgress();
        RestClient.build(this, true).deleteUser(id, new Callback<ResponseBase>() {
            @Override
            public void success(ResponseBase responseBase, Response response) {
                if (responseBase.getStatus_code() != 200) {
                    showAlert(getString(R.string.error), responseBase.getMessage());
                }
                hideProgress();
            }

            @Override
            public void failure(RetrofitError error) {
                hideProgress();
            }
        });
    }

    @Override
    public void optionProfile(final Profile profile) {
        MaterialDialog.Builder builder = new MaterialDialog.Builder(this);
        if (Utils.isBlank(profile.getPasscode())) {
            builder.items(R.array.set_pass_code);
        } else {
            builder.items(R.array.change_remove_pass_code);
        }
        builder.negativeText(R.string.cancel)
                .itemsCallbackSingleChoice(-1, new MaterialDialog.ListCallbackSingleChoice() {
                    @Override
                    public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                        if (text.toString().equalsIgnoreCase(getString(R.string.set_pass_code))) {
                            Intent intent = new Intent(FamilyMembersActivity.this, InputPassCodeActivity.class);
                            startActivityForResult(intent, REQUEST_SET_PASS_CODE);
                        } else if (text.toString().equalsIgnoreCase(getString(R.string.remove_pass_code))) {
                            Intent intent = new Intent(FamilyMembersActivity.this, InputPassCodeActivity.class);
                            intent.putExtra(Constants.CONFIRM_PASS_CODE_EXTRAS, profile.getPasscode());
                            startActivityForResult(intent, REQUEST_REMOVE_PASS_CODE);
                        } else if (text.toString().equalsIgnoreCase(getString(R.string.change_pass_code))) {
                            Intent intent = new Intent(FamilyMembersActivity.this, InputPassCodeActivity.class);
                            intent.putExtra(Constants.PASS_CODE_EXTRAS, profile.getPasscode());
                            startActivityForResult(intent, REQUEST_SET_PASS_CODE);
                        }
                        return true;
                    }
                }).show();
    }

    @Override
    public void onGuest() {

    }

    private void inputPassCode(final Profile profile) {
        new MaterialDialog.Builder(this)
                .title(R.string.please_enter_passcode)
                .positiveText(R.string.ok)
                .negativeText(R.string.cancel)
                .inputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_TEXT_VARIATION_PASSWORD)
                .inputRange(0, 6)
                .input(null, null, new MaterialDialog.InputCallback() {
                    @Override
                    public void onInput(MaterialDialog dialog, CharSequence input) {
                        if (profile.getPasscode().equalsIgnoreCase(input.toString())) {
                            PrefUtils.setInt(FamilyMembersActivity.this, PrefUtils.PREF_PROFILE_ID, Integer.valueOf(profile.getId()));
                            setResult(RESULT_OK);
                            finish();
                        } else {
                            showAlert(getString(R.string.error), getString(R.string.error_passcode));
                        }
                    }
                }).show();
    }

    private void setPassCode(String passCode) {
        showProgress();
        RestClient.build(this, true).setPasscode(PrefUtils.getInt(this, PrefUtils.PREF_PROFILE_ID), passCode, new Callback<ResponseBase>() {
            @Override
            public void success(ResponseBase responseBase, Response response) {
                if (responseBase.getStatus_code() != 200) {
                    showAlert(getString(R.string.error), responseBase.getMessage());
                }
                getData();
            }

            @Override
            public void failure(RetrofitError error) {
                hideProgress();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_SET_PASS_CODE && resultCode == InputPassCodeActivity.RESPONSE_SET_PASS_CODE) {
            String passCode = data.getStringExtra(Constants.PASS_CODE_EXTRAS);
            if (!Utils.isBlank(passCode)) {
                setPassCode(passCode);
            }
        }
        if (requestCode == REQUEST_REMOVE_PASS_CODE && resultCode == InputPassCodeActivity.RESPONSE_CONFIRM_PASS_CODE) {
            boolean passCode = data.getBooleanExtra(Constants.CONFIRM_PASS_CODE_EXTRAS, false);
            if (passCode) {
                setPassCode("");
            }
        }
        if (requestCode == REQUEST_ADD_PROFILE && resultCode == RESULT_OK) {
            mProfileMainId = 0;
            mListView.setAdapter(null);
            getData();
        }
    }
}
